package com.example.linearlayoutdemo;

import android.Manifest;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;

import com.example.linearlayoutdemo.networkstate.NetworkChangeReceiver;
import com.example.linearlayoutdemo.networkstate.NetworkMonitor;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HomeActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private HomeFragment homeFragment;
    private MineFragment mineFragment;
    private Button btnHome;
    private Button btnMine;
    private UserViewModel userViewModel;
    private String currentShowTag = "home_fragment"; // 手动记录当前显示的标签

//    private NetworkChangeReceiver networkReceiver;
    private NetworkMonitor networkMonitor;

    private static final String TAG2 = "NetworkTest";
    private ConnectivityManager connectivityManager;

    // 1. 声明 Callback 变量，方便后续注销
    private ConnectivityManager.NetworkCallback networkCallback;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: Activity创建");
        setContentView(R.layout.activity_home);
        // 1. 申请权限（定位 + 存储）
        requestPermissions();
//        // 1. 创建系统广播接收器实例
//        networkReceiver = new NetworkChangeReceiver();
//
//        // 2. 创建 IntentFilter，指定监听“网络变化”的 action
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//
//        // 3. 动态注册系统广播（通过 Context 注册，无需 LocalBroadcastManager）
//        registerReceiver(networkReceiver, filter);

//        // 初始化并开始监听网络变化
//        networkMonitor = new NetworkMonitor(this);
//        networkMonitor.startMonitoring();

        // 1. 获取 ConnectivityManager
        connectivityManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            Log.e(TAG, "无法获取 ConnectivityManager");
            return;
        }

        // 2. 创建最简单的 NetworkRequest
        NetworkRequest request = new NetworkRequest.Builder()
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .build();

        // 3. 创建极简回调
        networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                super.onAvailable(network);
                Log.d(TAG2, "onAvailable 触发");
                runOnUiThread(() -> Toast.makeText(HomeActivity.this, "网络可用", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onLost(Network network) {
                super.onLost(network);
                Log.d(TAG2, "onLost 触发");
                runOnUiThread(() -> Toast.makeText(HomeActivity.this, "网络断开", Toast.LENGTH_SHORT).show());
            }
        };

        // 4. 主线程注册
        connectivityManager.registerNetworkCallback(request, networkCallback);

        // 1. 初始化 ViewModel（和之前一样）
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

        // 2. 关键：接收登录页通过 Intent 传的邮箱
        String email = getIntent().getStringExtra("email");
        // 把登录页的邮箱传给 ViewModel（如果有值才传，避免空值）
        if (email != null && !email.isEmpty()) {
            userViewModel.setUserEmail(email);
        }



        // 初始化控件
        btnHome = findViewById(R.id.btn_home);
        btnMine = findViewById(R.id.btn_mine);

        if(savedInstanceState == null) {
            // 初始化Fragment
            homeFragment = new HomeFragment();
            mineFragment = new MineFragment();
            // 初始显示首页Fragment
            switchFragment(homeFragment,"home_fragment");
        } else
        {
            homeFragment = (HomeFragment) getSupportFragmentManager().findFragmentByTag("home_fragment");
            mineFragment = (MineFragment) getSupportFragmentManager().findFragmentByTag("mine_fragment");
            if(mineFragment == null)
                mineFragment = new MineFragment();
            currentShowTag = savedInstanceState.getString("CURRENT_SHOW_TAG", "home_fragment");
            if(TextUtils.equals(currentShowTag, "home_fragment") )
                switchFragment(homeFragment,"home_fragment");
            else
                switchFragment(mineFragment,"mine_fragment");
        }

        // 设置底部按钮点击事件
        btnHome.setOnClickListener(v -> switchFragment(homeFragment,"home_fragment"));
        btnMine.setOnClickListener(v -> switchFragment(mineFragment,"mine_fragment"));

    }
    // 切换Fragment
    private void switchFragment(Fragment targetFragment, String tag) {
        currentShowTag = tag;
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        // 如果目标Fragment没有被添加，则添加它
        if (!targetFragment.isAdded()) {
            transaction.add(R.id.fragment_container, targetFragment, tag);
        }

        // 隐藏所有Fragment
        if (homeFragment.isAdded()) {
            transaction.hide(homeFragment);
        }
        if (mineFragment.isAdded()) {
            transaction.hide(mineFragment);
        }

        // 显示目标Fragment
        transaction.show(targetFragment);
        transaction.commit();

        // 更新按钮状态
        updateButtonState(targetFragment);
    }

    // 更新按钮状态
    private void updateButtonState(Fragment currentFragment) {
        btnHome.setSelected(currentFragment instanceof HomeFragment);
        btnMine.setSelected(currentFragment instanceof MineFragment);
    }
    // 给 Fragment 提供 ViewModel 的方法（不变）
    public UserViewModel getUserViewModel() {
        return userViewModel;
    }

    // 动态申请权限（Android 6.0+）
    private void requestPermissions() {
        List<String> permissions = new ArrayList<>();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
        }
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        if (!permissions.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissions.toArray(new String[0]), 100);
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: Activity可见");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: Activity可交互");
            Boolean homefragmentshow = homeFragment.isVisible();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: Activity失去焦点");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: Activity不可见");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: Activity销毁");
        // 4. 注销系统广播（必须！否则内存泄漏）
//        unregisterReceiver(networkReceiver);
//        networkMonitor.stopMonitoring();
        connectivityManager.unregisterNetworkCallback(networkCallback);
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("CURRENT_SHOW_TAG", currentShowTag);
    }
}